<?php
/**
 * Created by PhpStorm.
 * User: shellvon
 * Date: 2018/2/6
 * Time: 下午2:10
 */

namespace App\Http\Controllers;


use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;

class WechatController extends Controller
{
    protected $app;

    public function __construct()
    {
        $config = [
            'app_id' => env('WECHAT_RED_PACKET_APPID'),
            'secret' => env('WECHAT_RED_PACKET_APPKEY'),
            'log' => [
                'level' => 'debug',
                'permission' => 0777,
                'file' => storage_path('logs/easywechat_' . date('Ymd') . '.log'),
            ],
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/wechat/callback',
            ],
        ];
        $this->app = Factory::officialAccount($config);
    }

    public function callback()
    {
        session_start();
        $oauth = $this->app->oauth;
        $user = $oauth->user();
        $originalInfo = $user->getOriginal();
        DB::table('template_user')->updateOrInsert(
            [
                'wx_openid' => $user->getId(),
                'unionid' => $originalInfo['unionid'] ?? ''
            ],
            [
                'nickname' => $user->getNickname(),
                'create_time' => time(),
                'update_time' => time(),
            ]
        );
        $_SESSION['wechat_user'] = $user->toArray();
        return View('bind',['msg' => '绑定成功']);
    }

    public function profile()
    {
        session_start();
        $oauth = $this->app->oauth;
        if (empty($_SESSION['wechat_user'])) {
            return $oauth->redirect();
        }
        $user = $_SESSION['wechat_user'];
        return View('bind',['msg' => '已经绑定成功了哦']);
    }

}
